<?php
namespace app\api\controller\vppz;

use \app\admin\model\vppz\Area as AreaModel;

class App extends AppBase
{
    //protected $noNeedLogin = ['*'];
    //protected $noNeedRight = ['*'];

	protected $AreaModel;

	// protected $_cfg = null; 在AppBase中
	// protected $_mine = null; 在AppBase中

	protected $_area = null;

    public function _initialize(){
        parent::_initialize();

		// 运营区域
		$this->AreaModel = new AreaModel;

		// 运营区选择优先级：前端参数指定，用户信息中的，id最小的运营区
		$aid = input('aid',2);
		if(empty($aid)){
			$aid=$this->_mine['area_id'];
		}

		if(!empty($aid)){
			$this->_area=$this->AreaModel->where(['use_switch'=>1])->find($aid);
		}

		if(empty($this->_area)){
			$this->_area=$this->AreaModel->where(['use_switch'=>1])->find();
			if(empty($this->_area)){
				$this->error('当前尚未开放运营区域');
			}
		}
		// 是否需要更新用户所在运营区
		if($this->_area['id'] != $this->_mine['area_id']){
			$this->_mine['area_id']=$this->_area['id'];
			$this->UserModel->save(['area_id'=>$this->_area['id']],['app_id'=>$this->app_id,'id'=>$this->_mine['id']]);
		}

		// 推广者
		$fuid = input('fuid');
		if($fuid && $fuid>0 && $fuid!=$this->_mine['id']){
			if($fuid==$this->_mine['seller_id']){
				// 如果和现有相同，则更新绑定时间
				$this->UserModel->save(['seller_time'=>time()],['app_id'=>$this->app_id,'id'=>$this->_mine['id']]);
			}else if(!($this->_mine['seller_id']>0) || ($this->_area['seller_bind']>0 && $this->_area['seller_bind']*86400<(time()-$this->_mine['seller_time']))){
				// 如果和现有不同，且绑定时间超出，则更新绑定
				// 绑定时需判断该fuid是否是推广者
				$fuser = $this->UserModel->where(['app_id'=>$this->app_id,'id'=>$fuid])->find();
				if($fuser && $fuser['seller_switch']>0){
					$this->UserModel->save(['seller_id'=>$fuid,'seller_time'=>time()],['app_id'=>$this->app_id,'id'=>$this->_mine['id']]);
				}
			}
		}

		// 是否绑定服务者
		$stid = input('stid');
		if($stid && $stid>0 && $stid!=$this->_mine['my_staff_id']){
			$this->UserModel->save(['my_staff_id'=>$stid],['app_id'=>$this->app_id,'id'=>$this->_mine['id']]);
			$this->_mine['my_staff_id']=$stid;
		}

		/**
		$this->error($this->_mine['id'].'='.$this->_mine['area_id']);
		if($this->_mine['id']==39){
			$this->error($this->_area['id'].'-'.$this->_mine['area_id']);
		}
		**/

    }


	// 应用初始化
	// 返回 应用配置、用户信息、当前城市信息
	public function init(){

		// TODO 传回前端的 应用配置，运营区域信息，我的用户信息，需去除敏感信息！！！！！！！！！！！！！
		$this->success('',array(
			'cfg'=>$this->_cfg,
			'mine'=>$this->_mine,
			'area'=>$this->_area
		));
	}

}
